package com.turtle3d.user.visualizators;

import java.util.ArrayList;

import javax.media.j3d.Appearance;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.Material;
import javax.media.j3d.Shape3D;
import javax.vecmath.Color3f;
import javax.vecmath.Matrix4f;

import com.turtle3d.ResourceManager;
import com.turtle3d.formallanguage.VisualSymbol;
import com.turtle3d.formallanguage.symbol.Symbol;
import com.turtle3d.util.Randomizer;
import com.turtle3d.visualizator.VisualData;
import com.turtle3d.visualizator.VisualizatorAdapter;


public class Tree2 extends VisualizatorAdapter {

	/**
	 * @param args
	 */
	
	public BranchGroup visualize(VisualData visualData){
		BranchGroup branchGroup = new BranchGroup();
		
		ArrayList<VisualSymbol> visualSequence = visualData.getVisualSequence();
				
		for(int i=0;i<visualSequence.size();i++){
			
			VisualSymbol visualSymbol = visualSequence.get(i);
			
			if(!visualSymbol.getSymbol().equals(new Symbol("F")))
				continue;
			
			int depth = visualSymbol.getDepth();															
			Float d = visualSymbol.getSymbol().getParameter("distance");
			float normalizedDepth = depth/(visualData.getMaximalDepthReached()*1f);
			Float r = visualSymbol.getSymbol().getParameter("radius");
									
			if (depth<visualData.getMaximalDepthReached()-1) {
				Shape3D trunk = ResourceManager.getShape3D("trunk2");

				trunk.setName("Trunk");

				Matrix4f scale = new Matrix4f();
				scale.setIdentity();
				scale.setScale(d);
				scale.m00=visualSymbol.getSymbol().getParameter(Symbol.RADIUS);
				scale.m22=visualSymbol.getSymbol().getParameter(Symbol.RADIUS);
				Matrix4f transform = visualSymbol.getTransform();
				transform.mul(scale);

				branchGroup.addChild(createTransformGroup(transform, trunk));
			} else {
				Shape3D leaf = ResourceManager.getShape3D("face_leaf");
												
				Appearance appearance = new Appearance();
				Material m = new Material();					
				m.setDiffuseColor(randomizeLeafColor());
				appearance.setMaterial(m);
				leaf.setAppearance(appearance);	
				
				leaf.setName("Leafs");
				
				Matrix4f scale = new Matrix4f();
				scale.setIdentity();																
				scale.setScale(visualSymbol.getSymbol().getParameter("leafSize"));
				Matrix4f transform = visualSymbol.getTransform();
				transform.mul(scale);								

				branchGroup.addChild(createTransformGroup(transform, leaf));
			}
			
		}					
		
		return branchGroup;
	}
	
	private Color3f randomizeLeafColor(){
		Color3f leafColor;
		int rand = Randomizer.getRandomizer().getRandom().nextInt(3);
		if(rand==0)
			leafColor = new Color3f(1f,0,0);
		else if(rand==1)
			leafColor = new Color3f(0,1f,0);
		else
			leafColor = new Color3f(0,0,1f);
		
		return leafColor;
	}

}
